package cn.mania_man.trpg_helper_server.controller;

import cn.mania_man.trpg_helper_server.room.Room;
import com.alibaba.fastjson.JSON;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.util.Optional;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
public class RoomController {
    @GetMapping({"/room/build/{roomName}/{roomPassword}/{roomEnterPassword}"})
    public String build(@PathVariable String roomName, @PathVariable String roomPassword, @PathVariable String roomEnterPassword) {
        if (Room.getRoomSet().stream().anyMatch((ele) -> ele.getName().equals(roomName))) {
            return "重复的房间名";
        }
        Room room = new Room();
        room.setPassword(roomPassword);
        room.setEnterPassword(roomEnterPassword);
        room.setName(roomName);
        Room.getRoomSet().add(room);
        return "成功创建房间";
    }
    @GetMapping("/room/build/{roomName}/{roomPassword}")
    public String build(@PathVariable String roomName, @PathVariable String roomPassword){
        return  build(roomName,roomPassword,null);
    }
    @GetMapping("/room/list")
    public String list(){
        return JSON.toJSONString(Room.getRoomSet().stream().map(Room::getName).collect(Collectors.toSet()));
    }
    @GetMapping("/room/close/{roomName}/{roomPassword}")
    public String close(@PathVariable String roomName, @PathVariable String roomPassword){
        Optional<Room> room = Room.getRoomSet().stream().filter(r->r.getName().equals(roomName)).findFirst();
        if (!room.isPresent()) return "没有匹配的房间";
        if (!room.get().getPassword().equals(roomPassword)) return "权限码错误";
        room.get().close();
        Room.getRoomSet().remove(room.get());
        return "成功关闭房间";
    }
}
